package com.teichmann.core.targets.online;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.htmlparser.Tag;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.teichmann.bo.Car;
import com.teichmann.core.OnlinePageJSoup;
import com.teichmann.core.annotations.Url;
import com.teichmann.core.util.ConnectionUtils;
import com.teichmann.core.util.CrawlerUtils;

@Url(value = "http://www.autocarro.com.br/autobusca.php")
public class AutoCarroJSoup implements OnlinePageJSoup {

   ArrayList<Car> cars = new ArrayList<Car>();

   public ArrayList<Car> performSearch(String parameter) throws IOException {

      Map<String, String> parameters = new HashMap<String, String>();
      parameters.put("AutModelo", parameter);
      parameters.put("Tipo", "REV");

      String responseBody = ConnectionUtils.post(this.getClass().getAnnotation(Url.class).value(), parameters);
      int numberOfPages = 1000;

      for (int x = 0; x < numberOfPages; x++) {
         responseBody = ConnectionUtils.get("http://www.autocarro.com.br/autobusca.php?pagina=" + x + "&Tipo=REV&AutModelo=" + parameter);

         if (numberOfPages == 1000) {
            numberOfPages = org.apache.commons.lang.StringUtils.countMatches(responseBody, "autobusca.php?pagina");
         }

         Document doc = Jsoup.parseBodyFragment(responseBody);
         Elements elements = doc.getElementsByAttributeValueContaining("bgcolor", "#c0c0c0".toUpperCase());
         elements.addAll(doc.getElementsByAttributeValueContaining("bgcolor", "#ffffff".toUpperCase()));

         for (Element e : elements) {
            cars.add(extractInformation(e));
         }

      }

      return cars;

   }

   public Car extractInformation(Element line) {
      Car car = new Car();
      try {

         car.setModelo(CrawlerUtils.removeUnusedFields(line.child(0).childNode(1).childNode(0).toString()));
         car.setPlaca(CrawlerUtils.removeUnusedFields(line.child(1).childNode(1).childNode(0).toString()));
         car.setCor(CrawlerUtils.removeUnusedFields(line.child(3).childNode(1).childNode(0).toString()));
         car.setCombustivel(CrawlerUtils.removeUnusedFields(line.child(4).childNode(1).childNode(0).toString()));
         car.setValor(CrawlerUtils.removeUnusedFields(line.child(6).childNode(1).childNode(0).toString()));
         car.setUrl("http://www.autocarro.com.br/" + line.child(0).childNode(1).attr("href"));

      }
      catch (Exception e) {
         // e.printStackTrace();
      }

      return car;

   }

   public Car extractInformation(Tag line) throws IOException {
      // TODO Auto-generated method stub
      return null;
   }

}

